import Vue from 'vue';
import Axios from "axios";
import qs from "qs";
import {Message,Loading} from 'element-ui'

Axios.defaults.timeout = 15000;

Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

var loading = null;
// 添加请求拦截器
Axios.interceptors.request.use(function (config) {

    if (config.loading) {
        loading = Loading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
        })
    }

    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
Axios.interceptors.response.use(function (response) {

    if (response.config.loading) {
        loading.close();
    }

    if(response.data.status){
        // let resMsg = ErrorCodes[response.data.status] ? ErrorCodes[response.data.status] : '请求错误';
        let resMsg = '请求错误';

        if (response.data.status == 1 || response.data.status == "1") {
            let result = response.data;
            result.msg = "成功";
            return result;
        }else if(response.data.status == 200001 || response.data.status == '200001'){
            //appLogin()
            return Promise.reject({...response.data,msg: resMsg});
        } else {
            return Promise.reject({...response.data,msg: resMsg});
        }
    }else {
        return response.data;
    }

}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

const http = {
    //动态引入数据
    addErrorCode(data){
        // Object.assign(ErrorCodes,data);
        Object.assign(data);
    },
    get(url = '', params = '', loading = false, headers = {}) {
        return Axios.get(url, {params, loading, headers})
    },
    post(url = '', data = '', loading = false, headers = {},type='') {//type 是否转换stringify   0:不需要装换
        if(type=='0'){
            return Axios.post(url, data, {loading, headers})
        }else{
            return Axios.post(url, qs.stringify(data), {loading, headers})
        }
    },
    put(url = '', data = '', loading = false, headers = {}) {
        return Axios.put(url, qs.stringify(data), {loading, headers})
    },
    delete(url = '', params = '', loading = false, headers = {}) {
        return Axios.delete(url, {params, loading, headers})
    }
};

export default http;